package com.liziyi0914.morearmor.effect;

import com.liziyi0914.morearmor.PlayerManager;
import com.liziyi0914.morearmor.Utils;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.EntityDamageEvent;
import com.liziyi0914.morearmor.event.entity.WorldTickEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.TntEntity;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;

import java.util.HashMap;
import java.util.UUID;
import java.util.function.Predicate;

public class GunpowderEffect extends AbstractEffect {

    HashMap<UUID, Long> record = new HashMap<>();

    @Listener
    public void onTick(WorldTickEvent e) {
        for (Entity entity : e.getWorld().getEntities()) {
            if (entity instanceof LivingEntity livingEntity) {
                if (!predicateArmor().test(livingEntity)) {
                    continue;
                }
                Vec3d p = livingEntity.getPos();
                final ServerPlayerEntity playerEntity = PlayerManager.get(entity.getUuid());
                if (playerEntity == null) continue;
                World world = playerEntity.getServerWorld();
                world.getOtherEntities(playerEntity, new Box(p.getX() - 5, p.getY() - 5, p.getZ() - 5, p.getX() + 5, p.getY() + 5, p.getZ() + 5), en -> entity.getPos().distanceTo(en.getPos()) < 5)
                        .forEach(en -> {
                            if (!(en instanceof LivingEntity living) || en.getUuid().equals(playerEntity.getUuid())) {
                                return;
                            }
                            long time = record.getOrDefault(playerEntity.getUuid(), 0L);
                            if (System.currentTimeMillis() - time >= 1000) {
                                record.put(playerEntity.getUuid(), System.currentTimeMillis());
                                TntEntity tntEntity = new TntEntity(world, living.getX(), living.getY(), living.getZ(), playerEntity);
                                tntEntity.setFuse(5);
                                world.spawnEntity(tntEntity);
                            }
                        });
            }
        }
    }

    @Listener
    public void onExplode(EntityDamageEvent e) {
        if (!e.getSource().isExplosive() || !predicateArmor().test(e.getEntity())) {
            return;
        }
        if (e.getEntity().getEntityWorld() instanceof ServerWorld) {
            e.setCanceled(true);
        }
    }

    @Override
    public Predicate<LivingEntity> predicateArmor() {
        return Utils.hasItemArmor(Items.GUNPOWDER);
    }
}
